<?php
// +----------------------------------------------------------------------
// | 功能:配送单模块
// +----------------------------------------------------------------------
// | 作者:崔骏
// +----------------------------------------------------------------------
// | 时间:2025.03.11
// +----------------------------------------------------------------------
namespace app\keeper\controller;
use app\common\lib\Str;
use app\common\model\mysql\In;
use app\common\model\mysql\InProduct;
use app\common\model\mysql\Order;
use app\common\model\mysql\OrderBackBucket;
use app\common\model\mysql\OrderBackWater;
use app\common\model\mysql\OrderProductNormal;
use app\common\model\mysql\OrderProductReturn;
use app\common\model\mysql\OrderProductWater;
use app\common\model\mysql\OrderTask;
use app\common\model\mysql\OrderTicket;
use app\common\model\mysql\Out;
use app\common\model\mysql\OutProduct;
use app\common\model\mysql\Product;
use app\common\model\mysql\Send as SendModel;
use app\common\model\mysql\SendProduct;
use app\common\model\mysql\WarehouseSpaceProduct;
use app\common\model\mysql\Worker;
use think\facade\Db;

class Send extends AuthBase
{
    /**
     * 配送单列表
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function singleList(){
        $page = $this->request->param('pageNum', 1);//当前页
        $limit = $this->request->param('pageSize', 10);//每页显示条数
        if(empty($page) || empty($limit)){
            return show(config("status.error"),"缺少分页参数");
        }
        $where = [
            ['stateenum','<>',32],
            ['shop_id','=',$this->shopId],
            ['isdel','=','0']
        ];
        $field = "send_id,stateenum,outdate,backdate,adddate,worker_name_send,is_rollback";
        $sendList = (new SendModel())->getNormalSendList($where,$limit,$page,$field);
        // 处理结果数据，确保日期字段不为null
        foreach ($sendList['data'] as &$item) {
            $item['outdate'] = $item['outdate'] ?? "";
            $item['backdate'] = $item['backdate'] ?? "";
        }
        return show(config("status.success"),"配送单列表",$sendList['data']);
    }

    /**
     * 配送单历史
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function SingleHistoryList(){
        $page = $this->request->param('pageNum', 1);//当前页
        $limit = $this->request->param('pageSize', 10);//每页显示条数
        if(empty($page) || empty($limit)){
            return show(config("status.error"),"缺少分页参数");
        }
        $where = [
            ['stateenum','<>',32],
            ['shop_id','=',$this->shopId],
            ['worker_id_out|worker_id_in','=',$this->workerId],
            ['isdel','=','0']
        ];
        $field = "send_id,send_sn,totalcount,ordercount,stateenum,outdate,backdate,adddate,worker_name_send,cashierdate,back_money,back_ticketcount,back_bucketcount";
        $sendList = (new SendModel())->getNormalSendList($where,$limit,$page,$field);
        // 处理结果数据，确保日期字段不为null
        foreach ($sendList['data'] as &$item) {
            $item['outdate'] = $item['outdate'] ?? "";
            $item['backdate'] = $item['backdate'] ?? "";
            $item['cashierdate'] = $item['cashierdate'] ?? "";
        }
        return show(config("status.success"),"配送单历史",$sendList['data']);
    }

    /**
     * 配送单出厂审核页面
     * @return \think\response\Json
     */
    public function outSinglePage(){
        $sendId = $this->request->param('send_id');
        if(empty($sendId)){
            return show(config("status.error"),"缺少参数配送单id");
        }
        try {
            $items = $itemAs = $taskData = $Pitems = [];
            $where = [
                ['send_id','=',$sendId],
                ['stateenum','<>',1024],
                ['worker_id_send','<>',0],
            ];
            $orderIdArr = (new Order())->getNormalOrderFiledArr($where,'order_id');
            if($orderIdArr){
                $orderWhere = [
                    ['order_id','in',$orderIdArr]
                ];
                //送水统计
                $field = "product_id,product_name,sellcount";
                $orderProductWaterData = (new OrderProductWater())->getNormalOrderProductWater($orderWhere,$field);
                if($orderProductWaterData){
                    $item = []; // 初始化变量
                    if (!empty($orderProductWaterData)) {
                        foreach ($orderProductWaterData as $v) {
                            if (!isset($item[$v['product_id']])) {
                                $item[$v['product_id']] = $v;
                            } else {
                                $item[$v['product_id']]['sellcount'] += $v['sellcount'];
                            }
                        }

                        $items = []; // 初始化变量
                        foreach ($item as $value) {
                            $items[] = [
                                'product_id'   => $value['product_id'],
                                'product_name' => $value['product_name'],
                                'sellcount'    => $value['sellcount'],
                                'typeenum'     => 1,
                            ];
                        }
                    }
                }
                //送产品统计
                $orderProductNormalData = (new OrderProductNormal())->getNormalOrderProductNormal($orderWhere,$field);
                if($orderProductNormalData){
                    $Pitem = []; // 初始化变量
                    if (!empty($orderProductNormalData)) {
                        foreach ($orderProductNormalData as $v) {
                            if (!isset($Pitem[$v['product_id']])) {
                                $Pitem[$v['product_id']] = $v;
                            } else {
                                $Pitem[$v['product_id']]['sellcount'] += $v['sellcount'];
                            }
                        }

                        $Pitems = []; // 初始化变量
                        foreach ($Pitem as $value) {
                            $Pitems[] = [
                                'product_id'   => $value['product_id'],
                                'product_name' => $value['product_name'],
                                'sellcount'    => $value['sellcount'],
                                'typeenum'     => 1,
                            ];
                        }
                    }
                }
                //送水票统计
                $field = "ticket_id,ticket_name,count_give,count_cost";
                $orderTicketData = (new OrderTicket())->getNormalOrderTicket($orderWhere,$field);
                if($orderTicketData){
                    $itemA = []; // 初始化变量
                    if (!empty($orderTicketData)) {
                        foreach ($orderTicketData as $v) {
                            if (!isset($itemA[$v['ticket_id']])) {
                                $itemA[$v['ticket_id']] = $v;
                            } else {
                                $itemA[$v['ticket_id']]['count_give'] += $v['count_give'];
                                $itemA[$v['ticket_id']]['count_cost'] += $v['count_cost'];
                            }
                        }

                        $itemAs = []; // 初始化变量
                        foreach ($itemA as $value) {
                            $itemAs[] = [
                                'ticket_id'     => $value['ticket_id'],
                                'ticket_name'   => $value['ticket_name'],
                                'count_give'    => $value['count_give'],
                                'count_cost'    => $value['count_cost'],
                            ];
                        }
                    }
                }
                //任务统计
                $field = "order_task_id,tname as task_name,tmoney as task_money";
                $taskData = (new OrderTask())->getNormalOrderTask($orderWhere,$field);
            }
            $field = "send_id,backdate,outdate,adddate,worker_name_send";
            $sendData = (new SendModel())->getSendFind([['send_id','=',$sendId]],$field);
            $sendData['outdate'] = $sendData['outdate']??"";
            $sendData['backdate'] = $sendData['backdate']??"";
            $goodsData = array_merge($items,$Pitems);
            $data = array(
                'sendData'      => $sendData,
                'goodsData'     => $goodsData,
                'ticketData'    => $itemAs,
                'taskData'      => $taskData,
            );
            return show(config("status.success"),"配送单出厂审核页面",$data);
        }catch (\Exception $e){
            return show(config("status.error"),$e->getMessage());
        }
    }

    /**
     * 配送单出厂审核
     * @return \think\response\Json
     */
    public function factoryAudit(){
        $sendId = $this->request->param('send_id');
        if(empty($sendId)){
            return show(config("status.error"),"缺少参数配送单id");
        }
        try {
            Db::startTrans(); // 开始事务
            $orderWhere = [
                ['send_id','=',$sendId],
                ['shop_id','=',$this->shopId],
                ['stateenum','<>',1024],
                ['worker_id_send','<>',0],
                ['iscancel','=',0]
            ];
            $orderIdArr = (new Order())->getNormalOrderFiledArr($orderWhere,'order_id');
            $PorderSellcount = 0;
            if($orderIdArr){
                $PorderSellcount = (new OrderProductNormal())->getOrderProductNormalSum([['order_id','in',$orderIdArr]]);
            }
            $orderWhere = [
                ['send_id','=',$sendId],
                ['shop_id','=',$this->shopId],
                ['stateenum','=',2],
                ['worker_id_send','<>',0],
                ['iscancel','=',0]
            ];
            $orderStatusData = (new Order())->getOrderFind($orderWhere);
            if($orderStatusData){
                return show(config("status.error"),"有订单未统计，请配送工先完成统计");
            }
            $sendWhere = [
                ['send_id','=',$sendId]
            ];
            $sendData = (new SendModel())->getSendFind($sendWhere,"send_id,worker_id_send,stateenum,totalcount");
            if($sendData['stateenum'] == 1){
                return show(config("status.error"),"订单信息已改变，请配送工重新统计");
            }
            if($sendData['stateenum'] == 4){
                return show(config("status.error"),"配送单已出厂审核完毕，请勿再次审核");
            }
            $sendProductCount = (new SendProduct())->getSendProductSum($sendWhere);
            if($sendProductCount != $PorderSellcount+$sendData['totalcount']){
                return show(config("status.error"),"配送单出厂商品与本次统计不符，请配送工重新统计");
            }
            $sendProductWhere = [
                ['send_id','=',$sendId],
                ['is_finish','=',2]
            ];
            $outGoodsDatas = (new SendProduct())->getNormalSendProduct($sendProductWhere,"product_id,product_name,tcount,warehouse_id,warehouse_space_id");
            if($outGoodsDatas){
                foreach ($outGoodsDatas as $value){
                    $productData = (new Product())->getProductFind([['product_id','=',$value['product_id']]],"shop_id,tcount,product_name");
                    if($productData['shop_id'] != $this->shopId){
                        return show(config("status.error"),"商品名称为".$productData['product_name']."的商品，不属于本店!请核实后再出厂");
                    }
                    if($productData['tcount'] < $value['tcount']){
                        return show(config("status.error"),"商品名称为".$productData['product_name']."的商品，库存不足!请核实后再出厂");
                    }
                }
            }
            $orderWhere = [
                ['send_id','=',$sendId],
                ['worker_id_send','<>',0],
                ['date_ticketgive','=',null],
            ];
            $orderTicketIdArr = (new Order())->getNormalOrderFiledArr($orderWhere,"order_id");
            if($orderTicketIdArr){
                $orderTicketChildData = (new OrderTicket())->getNormalOrderTicket([['order_id','in',$orderTicketIdArr]]);
                if($orderTicketChildData){
                    return show(config("status.error"),"审核失败，配送师傅请去收银处领水票再出厂");
                }
            }
            $sendProductWhere = [
                ['send_id','=',$sendId],
                ['tcount','=',0]
            ];
            $deleteSendProductRes = (new SendProduct())->deleteAllSendProduct($sendProductWhere);
            $sendSaveData['outdate']    = date("Y-m-d H:i:s",time());
            $sendSaveData['stateenum']  = 4;
            $sendSaveData['worker_id_out'] = $this->workerId;
            $sendSaveData['worker_name_out'] = $this->workerName;
            $sendSaveRes = (new SendModel())->saveSendData($sendId,$sendSaveData);
            if($sendSaveRes && $deleteSendProductRes !== false){
                $workerSaveData['sendstateenum'] = 4;
                (new Worker())->updateByWorkerId($sendData['worker_id_send'],$workerSaveData);
                foreach ($orderIdArr as $orderId){
                    $orderSaveData['stateenum'] = 4;
                    $orderSaveData['outdate'] = date("Y-m-d H:i:s",time());
                    $orderSaveData['worker_id_product_out'] = $this->workerId;
                    $orderSaveData['worker_name_product_out'] = $this->workerName;
                    (new Order())->saveOrderData($orderId,$orderSaveData);
                    (new Order())->saveIncOrderField($orderId,'count_out');
                }
                //添加出库单
                $outData['company_id']      = $this->companyId;
                $outData['shop_id']         = $this->shopId;
                $outData['order_sn']        = (new Str())->makeOrderNo($this->shopId,7);
                $outData['note']            = "";
                $outData['adddate']         = date("Y-m-d H:i:s",time());
                $outData['worker_id']       = $this->workerId;
                $outData['worker_name']     = $this->workerName;
                $outData['outtypeenum']     = 2;
                $outData['modeltypeenum']   = 5;
                $outData['modelid']         = $sendId;
                $outRes = (new Out())->addOutData($outData);
                if($outGoodsDatas){
                    foreach ($outGoodsDatas as $key=>$value){
                        $productData = (new Product())->getProductFind([['product_id','=',$value['product_id']]],"shop_id,tcount,product_name,price_unit,typeenum");
                        $outProductData[$key]['out_id']             = $outRes;
                        $outProductData[$key]['warehouse_id']       = $value['warehouse_id'];
                        $outProductData[$key]['warehouse_space_id'] = $value['warehouse_space_id'];
                        $outProductData[$key]['product_id']         = $value['product_id'];
                        $outProductData[$key]['tcount']             = $value['tcount'];
                        $outProductData[$key]['price_unit']         = $productData['price_unit'];
                        $outProductData[$key]['producttypeenum']    = $productData['typeenum'];
                        $outProductData[$key]['count_before']       = $productData['tcount'];
                        $outProductData[$key]['count_after']        = $productData['tcount']-$value['tcount'];
                        $outProductData[$key]['adddate']            = date("Y-m-d H:i:s",time());
                        $warehouseSpaceProductWhere = [
                            ['warehouse_id','=',$value['warehouse_id']],
                            ['warehouse_space_id','=',$value['warehouse_space_id']],
                            ['product_id','=',$value['product_id']],
                            ['isdel','=','0']
                        ];
                        (new WarehouseSpaceProduct())->saveDecWarehouseSpaceProductField($warehouseSpaceProductWhere,'tcount',$value['tcount']);
                        (new Product())->saveDecProductField([['product_id','=',$value['product_id']]],'tcount',$value['tcount']);
                    }
                    (new OutProduct())->addAllOutProduct($outProductData);
                    $saveSendProductData['is_finish'] = 1;
                    (new SendProduct())->saveSendProductData([['send_id','=',$sendId]],$saveSendProductData);
                }
                (new SendModel())->saveIncSendField($sendId,'count_out');
            }
            // 提交事务
            Db::commit();
            return show(config('status.success'), "操作成功", ['success'=>200]);
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return show(config("status.error"), $e->getMessage());
        }
    }

    /**
     * 配送单入厂审核页面
     * @return \think\response\Json
     */
    public function inSinglePage(){
        $sendId = $this->request->param('send_id');
        if(empty($sendId)){
            return show(config("status.error"),"缺少参数配送单id");
        }
        try {
            $field = "id";
            $inWhere = [
                ['modelid','=',$sendId],
                ['intypeenum','=',2],
                ['modeltypeenum','=',5],
                ['is_waste','=',0]
            ];
            $inData = (new In())->getInFind($inWhere,$field);

            $field = "send_id,outdate,backdate,adddate,worker_id_send,worker_name_send,is_rollback";
            $sendWhere = [
                ['send_id','=',$sendId],
                ['shop_id','=',$this->shopId],
            ];
            //配送单数据
            $sendData = (new SendModel())->getSendFind($sendWhere,$field);
            $sendData['outdate'] = $sendData['outdate']??"";
            $sendData['backdate'] = $sendData['backdate']??"";
            //送水统计
            $orderWhere = [
                ['send_id','=',$sendId],
                ['stateenum','in',[8,16,32]],
                ['worker_id_send','<>',0]
            ];
            $orderIdArr = (new Order())->getNormalOrderFiledArr($orderWhere,'order_id');
            $item = $waterNotGiveData = $waterNotGiveDatas = $backBucketData = $BucketData = $mortgageBucketData = $oweBucketData = $resellBucketData = $productData = $pledgeBucketData = [];
            $a = $b = $c = $d = $e = $f = 0;
            if($orderIdArr){
                $orderWaterWhere = [
                    ['order_id','in',$orderIdArr],
                    ['selltypeenum','<>',4]
                ];
                $field = "product_id,product_name,sellcount,bucketback_count_should as count_should,order_id,sellcount_real";
                $orderWaterData = (new OrderProductWater())->getNormalOrderProductWater($orderWaterWhere,$field);
                if($orderWaterData){
                    foreach ($orderWaterData as $value){
                        if(!isset($item[$value['product_id']])){
                            $item[$value['product_id']] = $value;
                        }else{
                            $item[$value['product_id']]['sellcount']        += $value['sellcount'];
                            $item[$value['product_id']]['count_should']     += $value['count_should'];
                            $item[$value['product_id']]['sellcount_real']   += $value['sellcount_real'];
                        }
                    }
                    foreach ($item as $value){
                        if($value['sellcount']>$value['sellcount_real']){
                            $orderBackWaterData = (new OrderBackWater())->getNormalBackWater([['order_id','=',$value['order_id']]],'product_id,product_name,tcount');
                            foreach ($orderBackWaterData as $v){
                                $productData = (new Product())->getProductFind([['parentid','=',$v['product_id']],['typeenum','=',8]]);
                                $backBucketData[$a]['product_id']   = $productData['product_id'];
                                $backBucketData[$a]['product_name'] = $productData['product_name'];
                                $backBucketData[$a]['tcount']       = $productData['tcount'];
                                $backBucketData[$a]['type']         = 2;
                                $backBucketData[$a]['producttypeenum'] = 8;
                                $a++;
                            }
                            $oweBarrelWhere = [
                                ['order_id','=',$value['order_id']],
                                ['product_id','=',$value['product_id']],
                                ['back_buckettypeenum','=',64]
                            ];
                            $oweBarrelCount = (new OrderBackBucket())->getNormalBackBucketSum($oweBarrelWhere,'tcount');
                            $waterNotGiveData[] = [
                                'product_id'    => $value['product_id'],
                                'product_name'  => $value['product_name'],
                                'tcount'        => $value['sellcount']-$value['sellcount_real']-$oweBarrelCount,
                                'count_should'  => 0,
                            ];
                        }
                        $productBucketData = (new Product())->getProductFind([['parentid','=',$value['product_id']],['typeenum','=',4]],'product_id');
                        $backBucketData[$a]['product_id']   = $productBucketData['product_id'];
                        $backBucketData[$a]['product_name'] = $value['product_name'];
                        $backBucketData[$a]['tcount']       = $value['count_should'];
                        $backBucketData[$a]['type']         = 1;
                        $backBucketData[$a]['producttypeenum'] = 4;
                        $a++;
                    }
                }
                $bucketChildData = (new OrderBackBucket())->getNormalBackBucket([['order_id','in',$orderIdArr]],'product_id,product_name,tcount,back_buckettypeenum,producttypeenum');
                if($bucketChildData){
                    foreach ($bucketChildData as $value){
                        //回桶类型,1回桶 2押桶 4还欠桶 8欠桶转押桶 16 欠桶转卖桶 32 退桶 64 欠桶 128 卖桶 256 不正常回桶 512 多回桶
                        if($value['back_buckettypeenum'] == 1){
                            $backBucketData[$a]['product_id']       = $value['product_id'];
                            $backBucketData[$a]['product_name']     = $value['product_name'];
                            $backBucketData[$a]['tcount']           = $value['tcount'];
                            $backBucketData[$a]['type']             = 2;
                            $backBucketData[$a]['producttypeenum']  = $value['producttypeenum'];
                            $a++;
                        }elseif ($value['back_buckettypeenum'] == 2){
                            $pledgeBucketData[$b]['product_id']     = $value['product_id'];
                            $pledgeBucketData[$b]['product_name']   = $value['product_name'];
                            $pledgeBucketData[$b]['tcount']         = $value['tcount'];
                            $pledgeBucketData[$b]['back_buckettypeenum'] = $value['back_buckettypeenum'];
                            $b++;
                        }elseif ($value['back_buckettypeenum'] == 4){
                            $BucketData[$c]['product_id']       = $value['product_id'];
                            $BucketData[$c]['product_name']     = $value['product_name'];
                            $BucketData[$c]['producttypeenum']  = $value['producttypeenum'];
                            $BucketData[$c]['tcount']           = $value['tcount'];
                            $BucketData[$c]['count_should']     = 0;
                            $c++;
                        }elseif ($value['back_buckettypeenum'] == 8){
                            $mortgageBucketData[$d]['product_id']     = $value['product_id'];
                            $mortgageBucketData[$d]['product_name']   = $value['product_name'];
                            $mortgageBucketData[$d]['tcount']         = $value['tcount'];
                            $mortgageBucketData[$d]['back_buckettypeenum'] = $value['back_buckettypeenum'];
                            $d++;
                        }elseif ($value['back_buckettypeenum'] == 16){
                            $resellBucketData[$e]['product_id']     = $value['product_id'];
                            $resellBucketData[$e]['product_name']   = $value['product_name'];
                            $resellBucketData[$e]['tcount']         = $value['tcount'];
                            $resellBucketData[$e]['back_buckettypeenum'] = $value['back_buckettypeenum'];
                            $e++;
                        }elseif ($value['back_buckettypeenum'] == 32){
                            $BucketData[$c]['product_id']       = $value['product_id'];
                            $BucketData[$c]['product_name']     = $value['product_name'];
                            $BucketData[$c]['producttypeenum']  = $value['producttypeenum'];
                            $BucketData[$c]['tcount']           = $value['tcount'];
                            $BucketData[$c]['count_should']     = 0;
                            $c++;
                        }elseif ($value['back_buckettypeenum'] == 64){
                            $oweBucketData[$f]['product_id']     = $value['product_id'];
                            $oweBucketData[$f]['product_name']   = $value['product_name'];
                            $oweBucketData[$f]['tcount']         = $value['tcount'];
                            $oweBucketData[$f]['back_buckettypeenum'] = $value['back_buckettypeenum'];
                            $f++;
                        }elseif($value['back_buckettypeenum'] == 256){
                            $BucketData[$c]['product_id']       = $value['product_id'];
                            $BucketData[$c]['product_name']     = $value['product_name'];
                            $BucketData[$c]['producttypeenum']  = $value['producttypeenum'];
                            $BucketData[$c]['tcount']           = $value['tcount'];
                            $BucketData[$c]['count_should']     = 0;
                            $c++;
                        }elseif($value['back_buckettypeenum'] == 512){
                            $BucketData[$c]['product_id']       = $value['product_id'];
                            $BucketData[$c]['product_name']     = $value['product_name'];
                            $BucketData[$c]['producttypeenum']  = $value['producttypeenum'];
                            $BucketData[$c]['tcount']           = $value['tcount'];
                            $BucketData[$c]['count_should']     = 0;
                            $c++;
                        }
                    }
                    $AbuckItem1 = [];
                    foreach ($backBucketData as $v) {
                        if (!isset($AbuckItem1[$v['product_id']])) {
                            $AbuckItem1[$v['product_id']] = [
                                'product_id' => $v['product_id'],
                                'product_name' => $v['product_name'],
                                'producttypeenum' => $v['producttypeenum'],
                                'tcount' => ($v['type'] == "2") ? $v['tcount'] : 0,
                                'count_should' => ($v['type'] == "2") ? 0 : $v['tcount']
                            ];
                        } else {
                            $AbuckItem1[$v['product_id']]['tcount'] += ($v['type'] == "2") ? $v['tcount'] : 0;
                            $AbuckItem1[$v['product_id']]['count_should'] += ($v['type'] == "2") ? 0 : $v['tcount'];
                        }
                    }
                    $backBucketDatas = array_merge($AbuckItem1,$BucketData);
                    $backBucketDatas = array_values($backBucketDatas);
                }

                $orderProductNormalData = (new OrderProductNormal())->getNormalOrderProductNormal([['order_id','in',$orderIdArr]],'product_id,product_name,sellcount,sellcount_real');
                if($orderProductNormalData){
                    foreach ($orderProductNormalData as $key=>$value){
                        if($value['sellcount'] == $value['sellcount_real']){
                            unset($orderProductNormalData[$key]);
                        }
                    }
                    $orderProductNormalData = array_merge($orderProductNormalData);
                    foreach ($orderProductNormalData as $key=>$value){
                        $orderProductNormalData[$key]['warehouse_name'] = "";
                        $orderProductNormalData[$key]['warehouse_space_name'] = "";
                        $orderProductNormalData[$key]['sellcount'] = $value['sellcount']-$value['sellcount_real'];
                        unset($orderProductNormalData[$key]['sellcount_real']);
                        $orderProductNormalData[$key]['saveGoods'] = (new WarehouseSpaceProduct())->getNormalWarehouseSpaceProductList([['a.product_id','=',$value['product_id']],['a.isdel','=','0']],'a.warehouse_space_product_id as id,a.warehouse_id,a.warehouse_space_id,b.warehouse_name,c.warehouse_space_name,a.tcount');
                        if($inData){
                            $inProductData = (new InProduct())->getNormalInProductFind([['a.in_id','=',$inData['id']],['a.product_id','=',$value['product_id']]],'b.warehouse_name,c.warehouse_space_name');
                            if($inProductData){
                                $orderProductNormalData[$key]['warehouse_name'] = $inProductData['warehouse_name'];
                                $orderProductNormalData[$key]['warehouse_space_name'] = $inProductData['warehouse_space_name'];
                            }
                        }
                    }
                }
            }

            //未送水统计
            $orderWhere = [
                ['send_id','=',$sendId],
                ['issendstateenum','=',1],
                ['stateenum','in',[4,16,32]],
                ['worker_id_send','<>',0],
                ['transfer_parentid','=',0]
            ];
            $orderIdNotArr = (new Order())->getNormalOrderFiledArr($orderWhere,'order_id');
            if($orderIdNotArr){
                $orderWaterData = (new OrderProductWater())->getNormalOrderProductWater([['order_id','in',$orderIdNotArr]],'product_id,sellcount,product_name,count_transfer,transfer_or_order_product_waterid');
                if($orderWaterData){
                    $Witem = [];
                    foreach ($orderWaterData as $v) {
                        if (!isset($Witem[$v['product_id']])) {
                            $Witem[$v['product_id']] = $v;
                            $Witem[$v['product_id']]['sellcount'] = $v['sellcount']-$v['count_transfer'];
                        }else{
                            $Witem[$v['product_id']]['sellcount'] += $v['sellcount']-$v['count_transfer'];
                        }
                    }
                    foreach ($Witem as $value) {
                        if($value['sellcount']>0){
                            $waterNotGiveDatas[] = array(
                                'product_id'    => $value['product_id'],
                                'product_name'  => $value['product_name'],
                                'tcount'        => $value['sellcount'],
                                'count_should'  => 0,
                            );
                        }
                    }
                }
                $productData = (new OrderProductNormal())->getNormalOrderProductNormal([['order_id','in',$orderIdNotArr]],'product_id,product_name,sellcount,count_transfer');
                if($productData){
                    foreach ($productData as $key=>$value){
                        $productData[$key]['sellcount'] = $value['sellcount']-$value['count_transfer'];
                        $productData[$key]['warehouse_name'] = "";
                        $productData[$key]['warehouse_space_name'] = "";
                        $productData[$key]['saveGoods'] = (new WarehouseSpaceProduct())->getNormalWarehouseSpaceProductList([['a.product_id','=',$value['product_id']],['a.isdel','=','0']],'a.warehouse_space_product_id as id,a.warehouse_id,a.warehouse_space_id,b.warehouse_name,c.warehouse_space_name,a.tcount');
                        if($inData){
                            $inProductData = (new InProduct())->getNormalInProductFind([['a.in_id','=',$inData['id']],['a.product_id','=',$value['product_id']]],'b.warehouse_name,c.warehouse_space_name');
                            if($inProductData){
                                $productData[$key]['warehouse_name'] = $inProductData['warehouse_name'];
                                $productData[$key]['warehouse_space_name'] = $inProductData['warehouse_space_name'];
                            }
                        }
                    }
                }
            }

            $waterNotGive = array_merge($waterNotGiveData,$waterNotGiveDatas);
            if($waterNotGive){
                foreach ($waterNotGive as $key=>$value){
                    $waterNotGive[$key]['warehouse_name'] = "";
                    $waterNotGive[$key]['warehouse_space_name'] = "";
                    $waterNotGive[$key]['saveGoods'] = (new WarehouseSpaceProduct())->getNormalWarehouseSpaceProductList([['a.product_id','=',$value['product_id']],['a.isdel','=','0']],'a.warehouse_space_product_id as id,a.warehouse_id,a.warehouse_space_id,b.warehouse_name,c.warehouse_space_name,a.tcount');
                    if($inData){
                        $inProductData = (new InProduct())->getNormalInProductFind([['a.in_id','=',$inData['id']],['a.product_id','=',$value['product_id']]],'b.warehouse_name,c.warehouse_space_name');
                        if($inProductData){
                            $waterNotGive[$key]['warehouse_name'] = $inProductData['warehouse_name'];
                            $waterNotGive[$key]['warehouse_space_name'] = $inProductData['warehouse_space_name'];
                        }
                    }
                }
            }

            if($backBucketDatas){
                foreach ($backBucketDatas as $key=>$value){
                    $backBucketDatas[$key]['warehouse_name'] = "";
                    $backBucketDatas[$key]['warehouse_space_name'] = "";
                    $backBucketDatas[$key]['saveGoods'] = (new WarehouseSpaceProduct())->getNormalWarehouseSpaceProductList([['a.product_id','=',$value['product_id']],['a.isdel','=','0']],'a.warehouse_space_product_id as id,a.warehouse_id,a.warehouse_space_id,b.warehouse_name,c.warehouse_space_name,a.tcount');
                    if($inData){
                        $inProductData = (new InProduct())->getNormalInProductFind([['a.in_id','=',$inData['id']],['a.product_id','=',$value['product_id']]],'b.warehouse_name,c.warehouse_space_name');
                        if($inProductData){
                            $backBucketDatas[$key]['warehouse_name'] = $inProductData['warehouse_name'];
                            $backBucketDatas[$key]['warehouse_space_name'] = $inProductData['warehouse_space_name'];
                        }
                    }
                }
            }

            //退货
            $orderWhere = [
                ['send_id','=',$sendId],
                ['stateenum','in',[8,16,32]],
                ['worker_id_send','<>',0],
            ];
            $orderReturnIdArr = (new Order())->getNormalOrderFiledArr($orderWhere,'order_id');
            if($orderReturnIdArr){
                $orderReturnChildData = (new OrderProductReturn())->getNormalOrderProductReturn([['order_id','in',$orderReturnIdArr],['isdel','=','0']],'product_id_bad as product_id,product_name_bad as product_name,tcount');
                if($orderReturnChildData){
                    foreach ($orderReturnChildData as $key=>$value){
                        $orderReturnChildData[$key]['warehouse_name'] = "";
                        $orderReturnChildData[$key]['warehouse_space_name'] = "";
                        $orderReturnChildData[$key]['saveGoods'] = (new WarehouseSpaceProduct())->getNormalWarehouseSpaceProductList([['a.product_id','=',$value['product_id']],['a.isdel','=','0']],'a.warehouse_space_product_id as id,a.warehouse_id,a.warehouse_space_id,b.warehouse_name,c.warehouse_space_name,a.tcount');
                        if($inData){
                            $inProductData = (new InProduct())->getNormalInProductFind([['a.in_id','=',$inData['id']],['a.product_id','=',$value['product_id']]],'b.warehouse_name,c.warehouse_space_name');
                            if($inProductData){
                                $orderReturnChildData[$key]['warehouse_name'] = $inProductData['warehouse_name'];
                                $orderReturnChildData[$key]['warehouse_space_name'] = $inProductData['warehouse_space_name'];
                            }
                        }
                    }
                }
            }
            $productDataArray = array_merge($orderProductNormalData,$productData);
            $data = [
                'sendData'=>$sendData,
                'waterData'=>$waterNotGive,
                'productData'=>$productDataArray,
                'backBucketData'=>$backBucketDatas,
                'pledgeBucketData'=>$pledgeBucketData,
                'mortgageBucketData'=>$mortgageBucketData,
                'resellBucketData'=>$resellBucketData,
                'oweBucketData'=>$oweBucketData,
                'orderReturnChildData'=>$orderReturnChildData,
            ];
            return show(config("status.success"),"配送单入厂审核页面",$data);
        }catch (\Exception $e){
            return show(config("status.error"),$e->getMessage());
        }
    }

    /**
     * 配送单入厂审核
     * @return \think\response\Json
     */
    public function inSingleAudit(){
        $sendId = $this->request->param('send_id');
        if(empty($sendId)){
            return show(config("status.error"),"缺少参数配送单id");
        }
        $goodsData = $this->request->param('goodsData');
        try {
            Db::startTrans(); // 开始事务
            $orderWhere = [
                ['send_id','=',$sendId],
                ['stateenum','=',4],
                ['iscancel','=',0],
                ['worker_id_send','<>',0]
            ];
            $passSendOrderData = (new Order())->getOrderFind($orderWhere);
            if($passSendOrderData){
                return show(config("status.error"),"有订单未完成配送,请先完成配送");
            }
            $sendWhere = [
                ['send_id','=',$sendId]
            ];
            $sendData = (new SendModel())->getSendFind($sendWhere,'stateenum,worker_id_send');
            if($sendData['stateenum'] == 16){
                return show(config("status.error"),"配送单已入厂审核完毕，请勿再次审核");
            }
            $inWhere = [
                ['intypeenum','=',2],
                ['modeltypeenum','=',5],
                ['modelid','=',$sendId],
                ['shop_id','=',$this->shopId],
                ['is_waste','=',0]
            ];
            $passInData = (new In())->getInFind($inWhere);
            if($passInData){
                return show(config("status.error"),"该笔配送单已完成商品入厂，请勿再次审核");
            }
            $goodsDataNew = $this->inSinglePageData($sendId);
            array_multisort(array_column($goodsData, 'product_id'), SORT_DESC, $goodsData);
            array_multisort(array_column($goodsDataNew, 'product_id'), SORT_DESC, $goodsDataNew);
            if($goodsData != $goodsDataNew){
                return show(config("status.error"),"该笔配送单数据已更新，请刷新页面");
            }
            $sendSaveData['stateenum'] = 16;
            $sendSaveData['backdate'] = date("Y-m-d H:i:s",time());
            $sendSaveData['worker_id_in'] = $this->workerId;
            $sendSaveData['worker_name_in'] = $this->workerName;
            $sendSaveRes = (new SendModel())->saveSendData($sendId,$sendSaveData);
            if(empty($sendSaveRes)){
                return show(config("status.error"),"修改配送单数据失败");
            }
            if(empty($goodsData)){
                $orderWhere = [
                    ['send_id','=',$sendId],
                    ['stateenum','=',4],
                    ['worker_id_send','<>',0]
                ];
                $orderIdArr = (new Order())->getNormalOrderFiledArr($orderWhere,'order_id');
                if($orderIdArr){
                    foreach ($orderIdArr as $value){
                        $orderSaveData['stateenum'] = 16;
                        $orderSaveData['backdate'] = date("Y-m-d H:i:s",time());
                        $orderSaveData['issendstateenum'] = 1;
                        $orderSaveData['worker_id_product_in'] = $this->workerId;
                        $orderSaveData['worker_name_product_in'] = $this->workerName;
                        (new Order())->saveOrderData($value,$orderSaveData);
                    }
                }
                $orderWhere = [
                    ['send_id','=',$sendId],
                    ['stateenum','=',8],
                    ['worker_id_send','<>',0]
                ];
                $orderIdArr = (new Order())->getNormalOrderFiledArr($orderWhere,'order_id');
                if($orderIdArr){
                    foreach ($orderIdArr as $value){
                        $orderSaveData['stateenum'] = 16;
                        $orderSaveData['backdate'] = date("Y-m-d H:i:s",time());
                        $orderSaveData['issendstateenum'] = 2;
                        $orderSaveData['worker_id_product_in'] = $this->workerId;
                        $orderSaveData['worker_name_product_in'] = $this->workerName;
                        (new Order())->saveOrderData($value,$orderSaveData);
                    }
                }
            }else{
                $inAddData['company_id'] = $this->companyId;
                $inAddData['shop_id'] = $this->shopId;
                $inAddData['order_sn'] = (new Str())->makeOrderNo($this->shopId,6);
                $inAddData['worker_id'] = $this->workerId;
                $inAddData['worker_name'] = $this->workerName;
                $inAddData['adddate'] = date("Y-m-d H:i:s",time());
                $inAddData['note'] = "库管入库";
                $inAddData['intypeenum'] = 2;
                $inAddData['modeltypeenum'] = 5;
                $inAddData['modelid'] = $sendId;
                $inAddRes = (new In())->addInData($inAddData);
                if($inAddRes){
                    $inProductData = [];
                    foreach ($goodsData as $key=>$value){
                        $productData = (new Product())->getProductFind([['product_id','=',$value['product_id']]],'product_id,typeenum,price_unit,tcount');
                        $inProductData[$key]['in_id']           = $inAddRes;
                        $inProductData[$key]['warehouse_id']    = $value['warehouse_id'];
                        $inProductData[$key]['warehouse_space_id'] = $value['warehouse_space_id'];
                        $inProductData[$key]['product_id']      = $value['product_id'];
                        $inProductData[$key]['tcount']          = $value['count'];
                        $inProductData[$key]['price_unit']      = $productData['price_unit'];
                        $inProductData[$key]['producttypeenum'] = $productData['typeenum'];
                        $inProductData[$key]['count_before']    = $productData['tcount'];
                        $inProductData[$key]['count_after']     = $productData['tcount']+$value['count'];
                        $inProductData[$key]['adddate']         = date("Y-m-d H:i:s",time());
                        $spaceProductWhere = [
                            ['a.product_id','=',$value['product_id']],
                            ['a.warehouse_id','=',$value['warehouse_id']],
                            ['a.warehouse_space_id','=',$value['warehouse_space_id']],
                            ['a.isdel','=','0']
                        ];
                        $warehouseSpaceProductData = (new WarehouseSpaceProduct())->getNormalWarehouseSpaceProductFind($spaceProductWhere,'*');
                        if($warehouseSpaceProductData){
                            (new WarehouseSpaceProduct())->saveInWarehouseSpaceProductField([['warehouse_space_product_id','=',$warehouseSpaceProductData['warehouse_space_product_id']]],'tcount',$value['count']);
                        }else{
                            $space['warehouse_id'] = $value['warehouse_id'];
                            $space['warehouse_space_id'] = $value['warehouse_space_id'];
                            $space['product_id'] = $value['product_id'];
                            $space['tcount'] = $value['count'];
                            $space['company_id'] = $this->companyId;
                            $space['shop_id'] = $this->shopId;
                            (new WarehouseSpaceProduct())->addWarehouseSpaceProductData($space);
                        }
                        (new Product())->saveInProductField([['product_id','=',$value['product_id']]],'tcount',$value['count']);
                    }
                    (new InProduct())->addAllInProduct($inProductData);
                }
                $orderWhere = [
                    ['send_id','=',$sendId],
                    ['stateenum','=',4],
                    ['worker_id_send','<>',0]
                ];
                $orderIdArr = (new Order())->getNormalOrderFiledArr($orderWhere,'order_id');
                if($orderIdArr){
                    foreach ($orderIdArr as $value){
                        $orderSaveData['stateenum'] = 16;
                        $orderSaveData['backdate'] = date('Y-m-d H:i:s',time());
                        $orderSaveData['issendstateenum'] = 1;
                        $orderSaveData['worker_id_product_in'] = $this->workerId;
                        $orderSaveData['worker_name_product_in'] = $this->workerName;
                        (new Order())->saveOrderData($value,$orderSaveData);
                    }
                }
                $orderWhere = [
                    ['send_id','=',$sendId],
                    ['stateenum','=',8],
                ];
                $orderIdArr = (new Order())->getNormalOrderFiledArr($orderWhere,'order_id');
                if($orderIdArr){
                    foreach ($orderIdArr as $value){
                        $orderSaveData['stateenum'] = 16;
                        $orderSaveData['backdate'] = date('Y-m-d H:i:s',time());
                        $orderSaveData['issendstateenum'] = 2;
                        $orderSaveData['worker_id_product_in'] = $this->workerId;
                        $orderSaveData['worker_name_product_in'] = $this->workerName;
                        (new Order())->saveOrderData($value,$orderSaveData);
                    }
                }
            }
            if($sendData['worker_id_send']){
                $workerSaveData['sendstateenum'] = 16;
                (new Worker())->updateByWorkerId($sendData['worker_id_send'],$workerSaveData);
            }
            $orderWhere = [
                ['send_id','=',$sendId],
                ['stateenum','=',4],
                ['iscancel','=',1]
            ];
            $orderSaveData['backdate'] = date("Y-m-d H:i:s",time());
            $orderSaveData['stateenum'] = 16;
            (new Order())->saveOrderWhereData($orderWhere,$orderSaveData);
            $orderWhere = [
                ['send_id','=',$sendId],
                ['stateenum','=',2],
                ['iscancel','=',0]
            ];
            $orderSaveData['send_id'] = 0;
            (new Order())->saveOrderWhereData($orderWhere,$orderSaveData);
            // 提交事务
            Db::commit();
            return show(config("status.success"),"操作成功",['success'=>200]);
        }catch (\Exception $e){
            // 回滚事务
            Db::rollback();
            return show(config("status.error"),$e->getMessage());
        }
    }

    /**
     * 根据$sendId来查询入库商品数据
     * @param $sendId
     * @return array|\think\response\Json
     */
    public function inSinglePageData($sendId){
        try {
            $field = "id";
            $inWhere = [
                ['modelid','=',$sendId],
                ['intypeenum','=',2],
                ['modeltypeenum','=',5],
                ['is_waste','=',0]
            ];
            $inData = (new In())->getInFind($inWhere,$field);
            //送水统计
            $orderWhere = [
                ['send_id','=',$sendId],
                ['stateenum','in',[8,16,32]],
                ['worker_id_send','<>',0]
            ];
            $orderIdArr = (new Order())->getNormalOrderFiledArr($orderWhere,'order_id');
            $item = $waterNotGiveData = $waterNotGiveDatas = $backBucketData = $BucketData = $mortgageBucketData = $oweBucketData = $resellBucketData = $productData = $pledgeBucketData = [];
            $a = $b = $c = $d = $e = $f = 0;
            if($orderIdArr){
                $orderWaterWhere = [
                    ['order_id','in',$orderIdArr],
                    ['selltypeenum','<>',4]
                ];
                $field = "product_id,product_name,sellcount,bucketback_count_should as count_should,order_id,sellcount_real";
                $orderWaterData = (new OrderProductWater())->getNormalOrderProductWater($orderWaterWhere,$field);
                if($orderWaterData){
                    foreach ($orderWaterData as $value){
                        if(!isset($item[$value['product_id']])){
                            $item[$value['product_id']] = $value;
                        }else{
                            $item[$value['product_id']]['sellcount']        += $value['sellcount'];
                            $item[$value['product_id']]['count_should']     += $value['count_should'];
                            $item[$value['product_id']]['sellcount_real']   += $value['sellcount_real'];
                        }
                    }
                    foreach ($item as $value){
                        if($value['sellcount']>$value['sellcount_real']){
                            $orderBackWaterData = (new OrderBackWater())->getNormalBackWater([['order_id','=',$value['order_id']]],'product_id,product_name,tcount');
                            foreach ($orderBackWaterData as $v){
                                $productData = (new Product())->getProductFind([['parentid','=',$v['product_id']],['typeenum','=',8]]);
                                $backBucketData[$a]['product_id']   = $productData['product_id'];
                                $backBucketData[$a]['product_name'] = $productData['product_name'];
                                $backBucketData[$a]['tcount']       = $productData['tcount'];
                                $backBucketData[$a]['type']         = 2;
                                $backBucketData[$a]['producttypeenum'] = 8;
                                $a++;
                            }
                            $oweBarrelWhere = [
                                ['order_id','=',$value['order_id']],
                                ['product_id','=',$value['product_id']],
                                ['back_buckettypeenum','=',64]
                            ];
                            $oweBarrelCount = (new OrderBackBucket())->getNormalBackBucketSum($oweBarrelWhere,'tcount');
                            $waterNotGiveData[] = [
                                'product_id'    => $value['product_id'],
                                'product_name'  => $value['product_name'],
                                'tcount'        => $value['sellcount']-$value['sellcount_real']-$oweBarrelCount,
                                'count_should'  => 0,
                            ];
                        }
                        $productBucketData = (new Product())->getProductFind([['parentid','=',$value['product_id']],['typeenum','=',4]],'product_id');
                        $backBucketData[$a]['product_id']   = $productBucketData['product_id'];
                        $backBucketData[$a]['product_name'] = $value['product_name'];
                        $backBucketData[$a]['tcount']       = $value['count_should'];
                        $backBucketData[$a]['type']         = 1;
                        $backBucketData[$a]['producttypeenum'] = 4;
                        $a++;
                    }
                }
                $bucketChildData = (new OrderBackBucket())->getNormalBackBucket([['order_id','in',$orderIdArr]],'product_id,product_name,tcount,back_buckettypeenum,producttypeenum');
                if($bucketChildData){
                    foreach ($bucketChildData as $value){
                        //回桶类型,1回桶 2押桶 4还欠桶 8欠桶转押桶 16 欠桶转卖桶 32 退桶 64 欠桶 128 卖桶 256 不正常回桶 512 多回桶
                        if($value['back_buckettypeenum'] == 1){
                            $backBucketData[$a]['product_id']       = $value['product_id'];
                            $backBucketData[$a]['product_name']     = $value['product_name'];
                            $backBucketData[$a]['tcount']           = $value['tcount'];
                            $backBucketData[$a]['type']             = 2;
                            $backBucketData[$a]['producttypeenum']  = $value['producttypeenum'];
                            $a++;
                        }elseif ($value['back_buckettypeenum'] == 2){
                            $pledgeBucketData[$b]['product_id']     = $value['product_id'];
                            $pledgeBucketData[$b]['product_name']   = $value['product_name'];
                            $pledgeBucketData[$b]['tcount']         = $value['tcount'];
                            $pledgeBucketData[$b]['back_buckettypeenum'] = $value['back_buckettypeenum'];
                            $b++;
                        }elseif ($value['back_buckettypeenum'] == 4){
                            $BucketData[$c]['product_id']       = $value['product_id'];
                            $BucketData[$c]['product_name']     = $value['product_name'];
                            $BucketData[$c]['producttypeenum']  = $value['producttypeenum'];
                            $BucketData[$c]['tcount']           = $value['tcount'];
                            $BucketData[$c]['count_should']     = 0;
                            $c++;
                        }elseif ($value['back_buckettypeenum'] == 8){
                            $mortgageBucketData[$d]['product_id']     = $value['product_id'];
                            $mortgageBucketData[$d]['product_name']   = $value['product_name'];
                            $mortgageBucketData[$d]['tcount']         = $value['tcount'];
                            $mortgageBucketData[$d]['back_buckettypeenum'] = $value['back_buckettypeenum'];
                            $d++;
                        }elseif ($value['back_buckettypeenum'] == 16){
                            $resellBucketData[$e]['product_id']     = $value['product_id'];
                            $resellBucketData[$e]['product_name']   = $value['product_name'];
                            $resellBucketData[$e]['tcount']         = $value['tcount'];
                            $resellBucketData[$e]['back_buckettypeenum'] = $value['back_buckettypeenum'];
                            $e++;
                        }elseif ($value['back_buckettypeenum'] == 32){
                            $BucketData[$c]['product_id']       = $value['product_id'];
                            $BucketData[$c]['product_name']     = $value['product_name'];
                            $BucketData[$c]['producttypeenum']  = $value['producttypeenum'];
                            $BucketData[$c]['tcount']           = $value['tcount'];
                            $BucketData[$c]['count_should']     = 0;
                            $c++;
                        }elseif ($value['back_buckettypeenum'] == 64){
                            $oweBucketData[$f]['product_id']     = $value['product_id'];
                            $oweBucketData[$f]['product_name']   = $value['product_name'];
                            $oweBucketData[$f]['tcount']         = $value['tcount'];
                            $oweBucketData[$f]['back_buckettypeenum'] = $value['back_buckettypeenum'];
                            $f++;
                        }elseif($value['back_buckettypeenum'] == 256){
                            $BucketData[$c]['product_id']       = $value['product_id'];
                            $BucketData[$c]['product_name']     = $value['product_name'];
                            $BucketData[$c]['producttypeenum']  = $value['producttypeenum'];
                            $BucketData[$c]['tcount']           = $value['tcount'];
                            $BucketData[$c]['count_should']     = 0;
                            $c++;
                        }elseif($value['back_buckettypeenum'] == 512){
                            $BucketData[$c]['product_id']       = $value['product_id'];
                            $BucketData[$c]['product_name']     = $value['product_name'];
                            $BucketData[$c]['producttypeenum']  = $value['producttypeenum'];
                            $BucketData[$c]['tcount']           = $value['tcount'];
                            $BucketData[$c]['count_should']     = 0;
                            $c++;
                        }
                    }
                    $AbuckItem1 = [];
                    foreach ($backBucketData as $v) {
                        if (!isset($AbuckItem1[$v['product_id']])) {
                            $AbuckItem1[$v['product_id']] = [
                                'product_id' => $v['product_id'],
                                'product_name' => $v['product_name'],
                                'producttypeenum' => $v['producttypeenum'],
                                'tcount' => ($v['type'] == "2") ? $v['tcount'] : 0,
                                'count_should' => ($v['type'] == "2") ? 0 : $v['tcount']
                            ];
                        } else {
                            $AbuckItem1[$v['product_id']]['tcount'] += ($v['type'] == "2") ? $v['tcount'] : 0;
                            $AbuckItem1[$v['product_id']]['count_should'] += ($v['type'] == "2") ? 0 : $v['tcount'];
                        }
                    }
                    $backBucketDatas = array_merge($AbuckItem1,$BucketData);
                    $backBucketDatas = array_values($backBucketDatas);
                }

                $orderProductNormalData = (new OrderProductNormal())->getNormalOrderProductNormal([['order_id','in',$orderIdArr]],'product_id,product_name,sellcount,sellcount_real');
                if($orderProductNormalData){
                    foreach ($orderProductNormalData as $key=>$value){
                        if($value['sellcount'] == $value['sellcount_real']){
                            unset($orderProductNormalData[$key]);
                        }
                    }
                    $orderProductNormalData = array_merge($orderProductNormalData);
                    foreach ($orderProductNormalData as $key=>$value){
                        $orderProductNormalData[$key]['warehouse_name'] = "";
                        $orderProductNormalData[$key]['warehouse_space_name'] = "";
                        $orderProductNormalData[$key]['sellcount'] = $value['sellcount']-$value['sellcount_real'];
                        unset($orderProductNormalData[$key]['sellcount_real']);
                        $orderProductNormalData[$key]['saveGoods'] = (new WarehouseSpaceProduct())->getNormalWarehouseSpaceProductList([['a.product_id','=',$value['product_id']],['a.isdel','=','0']],'a.warehouse_space_product_id as id,a.warehouse_id,a.warehouse_space_id,b.warehouse_name,c.warehouse_space_name,a.tcount');
                        if($inData){
                            $inProductData = (new InProduct())->getNormalInProductFind([['a.in_id','=',$inData['id']],['a.product_id','=',$value['product_id']]],'b.warehouse_name,c.warehouse_space_name');
                            if($inProductData){
                                $orderProductNormalData[$key]['warehouse_name'] = $inProductData['warehouse_name'];
                                $orderProductNormalData[$key]['warehouse_space_name'] = $inProductData['warehouse_space_name'];
                            }
                        }
                    }
                }
            }

            //未送水统计
            $orderWhere = [
                ['send_id','=',$sendId],
                ['issendstateenum','=',1],
                ['stateenum','in',[4,16,32]],
                ['worker_id_send','<>',0],
                ['transfer_parentid','=',0]
            ];
            $orderIdNotArr = (new Order())->getNormalOrderFiledArr($orderWhere,'order_id');
            if($orderIdNotArr){
                $orderWaterData = (new OrderProductWater())->getNormalOrderProductWater([['order_id','in',$orderIdNotArr]],'product_id,sellcount,product_name,count_transfer,transfer_or_order_product_waterid');
                if($orderWaterData){
                    $Witem = [];
                    foreach ($orderWaterData as $v) {
                        if (!isset($Witem[$v['product_id']])) {
                            $Witem[$v['product_id']] = $v;
                            $Witem[$v['product_id']]['sellcount'] = $v['sellcount']-$v['count_transfer'];
                        }else{
                            $Witem[$v['product_id']]['sellcount'] += $v['sellcount']-$v['count_transfer'];
                        }
                    }
                    foreach ($Witem as $value) {
                        if($value['sellcount']>0){
                            $waterNotGiveDatas[] = array(
                                'product_id'    => $value['product_id'],
                                'product_name'  => $value['product_name'],
                                'tcount'        => $value['sellcount'],
                                'count_should'  => 0,
                            );
                        }
                    }
                }
                $productData = (new OrderProductNormal())->getNormalOrderProductNormal([['order_id','in',$orderIdNotArr]],'product_id,product_name,sellcount,count_transfer');
                if($productData){
                    foreach ($productData as $key=>$value){
                        $productData[$key]['sellcount'] = $value['sellcount']-$value['count_transfer'];
                        $productData[$key]['warehouse_name'] = "";
                        $productData[$key]['warehouse_space_name'] = "";
                        $productData[$key]['saveGoods'] = (new WarehouseSpaceProduct())->getNormalWarehouseSpaceProductList([['a.product_id','=',$value['product_id']],['a.isdel','=','0']],'a.warehouse_space_product_id as id,a.warehouse_id,a.warehouse_space_id,b.warehouse_name,c.warehouse_space_name,a.tcount');
                        if($inData){
                            $inProductData = (new InProduct())->getNormalInProductFind([['a.in_id','=',$inData['id']],['a.product_id','=',$value['product_id']]],'b.warehouse_name,c.warehouse_space_name');
                            if($inProductData){
                                $productData[$key]['warehouse_name'] = $inProductData['warehouse_name'];
                                $productData[$key]['warehouse_space_name'] = $inProductData['warehouse_space_name'];
                            }
                        }
                    }
                }
            }

            $waterNotGive = array_merge($waterNotGiveData,$waterNotGiveDatas);
            if($waterNotGive){
                foreach ($waterNotGive as $key=>$value){
                    $waterNotGive[$key]['warehouse_name'] = "";
                    $waterNotGive[$key]['warehouse_space_name'] = "";
                    $waterNotGive[$key]['saveGoods'] = (new WarehouseSpaceProduct())->getNormalWarehouseSpaceProductList([['a.product_id','=',$value['product_id']],['a.isdel','=','0']],'a.warehouse_space_product_id as id,a.warehouse_id,a.warehouse_space_id,b.warehouse_name,c.warehouse_space_name,a.tcount');
                    if($inData){
                        $inProductData = (new InProduct())->getNormalInProductFind([['a.in_id','=',$inData['id']],['a.product_id','=',$value['product_id']]],'b.warehouse_name,c.warehouse_space_name');
                        if($inProductData){
                            $waterNotGive[$key]['warehouse_name'] = $inProductData['warehouse_name'];
                            $waterNotGive[$key]['warehouse_space_name'] = $inProductData['warehouse_space_name'];
                        }
                    }
                }
            }

            if($backBucketDatas){
                foreach ($backBucketDatas as $key=>$value){
                    $backBucketDatas[$key]['warehouse_name'] = "";
                    $backBucketDatas[$key]['warehouse_space_name'] = "";
                    $backBucketDatas[$key]['saveGoods'] = (new WarehouseSpaceProduct())->getNormalWarehouseSpaceProductList([['a.product_id','=',$value['product_id']],['a.isdel','=','0']],'a.warehouse_space_product_id as id,a.warehouse_id,a.warehouse_space_id,b.warehouse_name,c.warehouse_space_name,a.tcount');
                    if($inData){
                        $inProductData = (new InProduct())->getNormalInProductFind([['a.in_id','=',$inData['id']],['a.product_id','=',$value['product_id']]],'b.warehouse_name,c.warehouse_space_name');
                        if($inProductData){
                            $backBucketDatas[$key]['warehouse_name'] = $inProductData['warehouse_name'];
                            $backBucketDatas[$key]['warehouse_space_name'] = $inProductData['warehouse_space_name'];
                        }
                    }
                }
            }

            //退货
            $orderWhere = [
                ['send_id','=',$sendId],
                ['stateenum','in',[8,16,32]],
                ['worker_id_send','<>',0],
            ];
            $orderReturnIdArr = (new Order())->getNormalOrderFiledArr($orderWhere,'order_id');
            if($orderReturnIdArr){
                $orderReturnChildData = (new OrderProductReturn())->getNormalOrderProductReturn([['order_id','in',$orderReturnIdArr],['isdel','=','0']],'product_id_bad as product_id,product_name_bad as product_name,tcount');
                if($orderReturnChildData){
                    foreach ($orderReturnChildData as $key=>$value){
                        $orderReturnChildData[$key]['warehouse_name'] = "";
                        $orderReturnChildData[$key]['warehouse_space_name'] = "";
                        $orderReturnChildData[$key]['saveGoods'] = (new WarehouseSpaceProduct())->getNormalWarehouseSpaceProductList([['a.product_id','=',$value['product_id']],['a.isdel','=','0']],'a.warehouse_space_product_id as id,a.warehouse_id,a.warehouse_space_id,b.warehouse_name,c.warehouse_space_name,a.tcount');
                        if($inData){
                            $inProductData = (new InProduct())->getNormalInProductFind([['a.in_id','=',$inData['id']],['a.product_id','=',$value['product_id']]],'b.warehouse_name,c.warehouse_space_name');
                            if($inProductData){
                                $orderReturnChildData[$key]['warehouse_name'] = $inProductData['warehouse_name'];
                                $orderReturnChildData[$key]['warehouse_space_name'] = $inProductData['warehouse_space_name'];
                            }
                        }
                    }
                }
            }
            $productDataArray = array_merge($orderProductNormalData,$productData);
            $datas = 0;
            foreach ($waterNotGive as $value){
                $data[$datas]['product_id']         = $value['product_id'];
                $data[$datas]['count']              = $value['tcount'];
                $data[$datas]['warehouse_id']       = $value['saveGoods'][0]['warehouse_id'];
                $data[$datas]['warehouse_space_id'] = $value['saveGoods'][0]['warehouse_space_id'];
                $datas++;
            }
            foreach ($backBucketDatas as $value){
                $data[$datas]['product_id']         = $value['product_id'];
                $data[$datas]['count']              = $value['tcount'];
                $data[$datas]['warehouse_id']       = $value['saveGoods'][0]['warehouse_id'];
                $data[$datas]['warehouse_space_id'] = $value['saveGoods'][0]['warehouse_space_id'];
                $datas++;
            }
            foreach ($orderReturnChildData as $value) {
                $data[$datas]['product_id']         = $value['product_id'];
                $data[$datas]['count']              = $value['tcount'];
                $data[$datas]['warehouse_id']       = $value['saveGoods'][0]['warehouse_id'];
                $data[$datas]['warehouse_space_id'] = $value['saveGoods'][0]['warehouse_space_id'];
                $datas++;
            }
            foreach ($productDataArray as $value) {
                $data[$datas]['product_id']         = $value['product_id'];
                $data[$datas]['count']              = $value['tcount'];
                $data[$datas]['warehouse_id']       = $value['saveGoods'][0]['warehouse_id'];
                $data[$datas]['warehouse_space_id'] = $value['saveGoods'][0]['warehouse_space_id'];
                $datas++;
            }
            return $data;
        }catch (\Exception $e){
            return show(config("status.error"),$e->getMessage());
        }
    }

}
